package canss.webservice.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import canss.supports.basic;
import canss.webservice.model.ModuleDesc;
import canss.webservice.service.PortalIntraWebServiceControl;
import canss.webservice.service.PortalIntraWebServiceControlBean;

public class getAjaxGetModuleStatusByMID extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet
{
	private static final long serialVersionUID = 745867796687621988L;

	public getAjaxGetModuleStatusByMID()
	{
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doPost(request, response);
	}
	
	private final class HashData
	{
		public String mid;
		public String status;
		public long timestamp;
		public long hashedtime;
		public HashData(String _mid, String _status, long _timestamp, long _hashedtime)
		{
			mid=_mid; status=_status; timestamp=_timestamp; hashedtime=_hashedtime;
		}
	}
	private static Hashtable<String, HashData> hashtable;
	static
	{
		if(hashtable==null)
			hashtable = new Hashtable<String, HashData>();
	}

	final long mintimerefresh = 3000;
	final long mintimedisconnected = 20000; //same to 'svtOPMIDDesc.java'
	PortalIntraWebServiceControl control;
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String _mid = request.getParameter("_mid");
		
		try
		{
			if( basic.isEmpty(_mid) )
				throw new IllegalArgumentException("missing mid");
			if (  !hashtable.containsKey(_mid) || 
					System.currentTimeMillis() > hashtable.get(_mid).hashedtime + mintimerefresh )
			{
				//out.write("from db");
				control = (control == null) ? new PortalIntraWebServiceControlBean() : control;
				ModuleDesc[] modulelist = control.getEntireModuleDesc();
				hashtable.clear();
				if(modulelist!=null && modulelist.length>0)
				{
					for(ModuleDesc module : modulelist)
						hashtable.put(module.getTBLMID_MID(), new HashData(module.getTBLMID_MID(), module.getMIDSTATUS(), module.getTIMESTAMP(), System.currentTimeMillis()));
				}
			}else
			{
				//out.write("from hash");
			}
			
			HashData catchdata = hashtable.get(_mid);
			if(catchdata!=null)
			{
				if(catchdata.timestamp + mintimedisconnected < System.currentTimeMillis())
					out.write("<span style='color:red'>disconnected</span>");
				else
					out.write("<span style='color:green'>"+catchdata.status+"</span>");
			}else
				out.write("-");
		}catch(Exception e)
		{
			out.write("error: " + e);
		}
	
	}
}